<template>
  <Row type="flex" justify="center" align="middle" class="login" @keydown.enter.native="submitLogin">
    <Col :xs="{span:22}" style="width: 368px;">
    <Row class="header">
      <img src="../../assets/meida.png" width="380px"  />
      <div class="description">互联网+终身学习的开发教育平台</div>
    </Row>

    <Alert type="error" show-icon v-if="error">{{errorMsg}}</Alert>

    <Row class="login-form" v-if="!socialLogining">
      <Tabs v-model="tabName">
        <TabPane label="企业端登录" name="username" icon="md-person">
          <Form ref="usernameLoginForm" :model="form" :rules="rules" class="form">
            <FormItem prop="username" style="padding-left: 20px;padding-right: 20px;">
              <Input v-model="form.username" prefix="ios-contact" size="large" clearable placeholder="请输入用户名" autocomplete="off" />
            </FormItem>
            <FormItem prop="password" style="padding-left: 20px;padding-right: 20px;">
              <Input type="password" v-model="form.password" prefix="ios-lock" size="large" clearable placeholder="请输入密码" autocomplete="off" />
            </FormItem>
          </Form>
        </TabPane>
       <!-- <TabPane label="手机号登录" name="mobile" icon="ios-phone-portrait">
          <Form ref="mobileLoginForm" :model="form" :rules="rules" class="form">
            <FormItem prop="mobile">
              <Input v-model="form.mobile" prefix="ios-phone-portrait" size="large" clearable placeholder="请输入手机号" />
            </FormItem>
            <FormItem prop="code" :error="errorCode">
              <Row type="flex" justify="space-between" class="code-row-bg">
                <Input v-model="form.code" prefix="ios-mail-outline" size="large" clearable placeholder="请输入短信验证码" :maxlength="maxLength" class="input-verify" />
                <Button size="large" :loading="sending" @click="sendVerify" v-if="!sended" class="send-verify">
                  <span v-if="!sending">获取验证码</span>
                  <span v-else>发送中</span>
                </Button>
                <Button size="large" disabled v-if="sended" class="count-verify">{{countButton}}</Button>
              </Row>
            </FormItem>
          </Form>
        </TabPane>-->
      </Tabs>

      <Row type="flex" justify="space-between" class="code-row-bg" style="padding-left: 20px;">
        <Checkbox v-model="saveLogin" size="large">自动登录</Checkbox>
        <!--<a class="forget-pass" @click="showAccount">忘记密码</a>-->
      </Row>
      <Row style="padding-left:20px;">
        <Button class="login-btn" type="primary" size="large" :loading="loading" @click="submitLogin" style="width: 310px;">
          <span v-if="!loading">登录</span>
          <span v-else>登录中...</span>
        </Button>
      </Row>

    </Row>
    <div v-if="socialLogining" class="spinner">
      <div class="rect1"></div>
      <div class="rect2"></div>
      <div class="rect3"></div>
      <div class="rect4"></div>
      <div class="rect5"></div>
      <!-- <span>用户数据加载中...</span> -->
    </div>

   <!-- <Row class="foot">
      <Row type="flex" justify="space-around" class="code-row-bg help">
        <a class="item" href="javascript:;" target="_blank">帮助</a>
        <a class="item" href="javascript:;" target="_blank">隐私</a>
        <a class="item" href="javascript:;" target="_blank">条款</a>
      </Row>
      <Row type="flex" justify="center" class="code-row-bg copyright">
        COPYRIGHT © 2004-2017 <a href="http://www.shenzhenmeida.com/" target="_blank" style="margin:0 5px;">勤博教育</a> 版权所有
      </Row>
    </Row>-->
    </Col>
    <Modal v-model="showVideo" title="微信授权登录" :styles="{top: '50px'}"  footer-hide width="50%">
      <iframe :src="iframesrc"  scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true" style="width:100%;height:550px;"> </iframe>
    </Modal>
  </Row>

</template>

<script>
    import Cookies from "js-cookie";
    import {
        login,
        userInfo,
        loginConfig,
        githubLogin,
        qqLogin,
        weiboLogin,
        getJWT,
        sendSms,
        smsLogin,
        getLogin
    } from "@/api/index";
    import util from "@/libs/util.js";
    export default {
        data() {
            const validateMobile = (rule, value, callback) => {
                var reg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error("手机号格式错误"));
                } else {
                    callback();
                }
            };
            return {
                socialLogining: true,
                error: false,
                showVideo:false,
                errorMsg: "",
                iframesrc:"",
                tabName: "username",
                saveLogin: true,
                loading: false,
                sending: false,
                sended: false,
                count: 60,
                countButton: "60 s",
                maxLength: 6,
                errorCode: "",
                form: {
                    username: "admin",
                    password: "123456",
                    mobile: "",
                    code: ""
                },
                config: {},
                rules: {
                    username: [
                        {
                            required: true,
                            message: "账号不能为空",
                            trigger: "blur"
                        }
                    ],
                    password: [
                        {
                            required: true,
                            message: "密码不能为空",
                            trigger: "blur"
                        }
                    ],
                    mobile: [
                        {
                            required: true,
                            message: "手机号不能为空",
                            trigger: "blur"
                        },
                        {
                            validator: validateMobile,
                            trigger: "blur"
                        }
                    ]
                }
            };
        },
        methods: {
            showErrorMsg(msg) {
                this.error = true;
                this.errorMsg = msg;
            },
            sendVerify() {
                this.$refs.mobileLoginForm.validate(valid => {
                    if (valid) {
                        this.sending = true;
                        sendSms(this.form.mobile).then(res => {
                            this.sending = false;
                            if (res.success) {
                                this.$Message.success("发送短信验证码成功");
                                this.sended = true;
                                this.countDown();
                            }
                        });
                    }
                });
            },
            countDown() {
                let that = this;
                if (this.count === 0) {
                    this.sended = false;
                    this.count = 60;
                    return;
                } else {
                    this.countButton = this.count + " s";
                    this.count--;
                }
                setTimeout(function() {
                    that.countDown();
                }, 1000);
            },
            submitLogin() {
                if (this.tabName === "username") {
                    this.$refs.usernameLoginForm.validate(valid => {
                        if (valid) {
                            this.loading = true;
                            login({
                                username: this.form.username,
                                password: this.form.password,
                                saveLogin: this.saveLogin
                            }).then(res => {
                                if (res.status === true) {
                                    this.setStore("accessToken", res.data.access_token);
                                    // 获取用户信息
                                    userInfo().then(res => {
                                        if (res.status === true) {
                                            // 避免超过大小限制
                                            delete res.data.authorities;
                                            let roles = [];
                                            var userInfo=res.data;
                                            if(userInfo.userType!='UT_COMPANY'){
                                              this.$Message.error("非法登录");
                                              return;
                                            }
                                            getLogin(res.data.companyId).then(ass => {
                                              if(ass.status === false){
                                                this.loading = false;
                                                return false;
                                              }
                                              res.data.roles.forEach(role => {
                                                roles.push(role.code);
                                              });
                                              this.setStore("roles", roles);
                                              if (this.saveLogin) {
                                                // 保存7天
                                                Cookies.set("userInfo", JSON.stringify(userInfo), {
                                                  expires: 7
                                                });
                                              } else {
                                                Cookies.set("userInfo", JSON.stringify(userInfo));
                                              }
                                              this.setStore("userInfo",userInfo);
                                              this.$store.commit("setAvatarPath", userInfo.avatar);
                                              // 加载菜单
                                              util.initRouter(this);
                                              this.$router.push({
                                                name: "home_index"
                                              });
                                            });
                                        } else {
                                            this.loading = false;
                                        }
                                    });
                                } else {
                                    this.loading = false;
                                }
                            });
                        }
                    });
                } else if (this.tabName === "mobile") {
                    this.$refs.mobileLoginForm.validate(valid => {
                        if (valid) {
                            if (this.form.code === "") {
                                this.errorCode = "验证码不能为空";
                                return;
                            } else {
                                this.errorCode = "";
                            }
                            this.loading = true;
                            smsLogin(this.form).then(res => {
                                if (res.success) {
                                    this.setStore("accessToken", res.result);
                                    // 获取用户信息
                                    userInfo().then(res => {
                                        if (res.success === true) {
                                          getLogin(res.data.companyId).then(ass => {
                                            if(ass.status === false){
                                              this.loading = false;
                                              return false;
                                            }
                                            // 避免超过大小限制
                                            delete res.result.permissions;
                                            let roles = [];
                                            res.result.roles.forEach(e => {
                                              roles.push(e.name);
                                            });
                                            this.setStore("roles", roles);
                                            if (this.saveLogin) {
                                              // 保存7天
                                              Cookies.set("userInfo", JSON.stringify(res.result), {
                                                expires: 7
                                              });
                                            } else {
                                              Cookies.set("userInfo", JSON.stringify(res.result));
                                            }
                                            this.setStore("userInfo", res.result);
                                            this.$store.commit("setAvatarPath", res.result.avatar);
                                            // 加载菜单
                                            util.initRouter(this);
                                            this.$router.push({
                                              name: "home_index"
                                            });
                                          });
                                        } else {
                                            this.loading = false;
                                        }
                                    });
                                } else {
                                    this.loading = false;
                                }
                            });
                        }
                    });
                }
            },
            handleLoginConfig(){
                loginConfig().then(res => {
                    this.config = res.data
                })
            },
            handleClick(type){
                let url = this.config[type]
                if (!url) return
                //this.openWin(url,type,650,500);
                this.iframesrc=url;
                this.showVideo=true;
               // window.location.href = url;
            },
            openWin(url, name, iWidth, iHeight) {
                //获得窗口的垂直位置
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //获得窗口的水平位置
                var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
                window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
            },
            toGithubLogin() {
                this.socialLogining = true;
                githubLogin().then(res => {
                    if (res.success) {
                        window.location.href = res.result;
                    } else {
                        this.socialLogining = false;
                    }
                });
            },
            toQQLogin() {
                this.socialLogining = true;
                qqLogin().then(res => {
                    if (res.success) {
                        window.location.href = res.result;
                    } else {
                        this.socialLogining = false;
                    }
                });
            },
            toWeiboLogin() {
                this.socialLogining = true;
                weiboLogin().then(res => {
                    if (res.success) {
                        window.location.href = res.result;
                    } else {
                        this.socialLogining = false;
                    }
                });
            },
            toWeixinLogin() {
                this.$Message.error("开通微信登录官方收费300/年");
            },
            relatedLogin() {
                let q = this.$route.query;
                let error = q.error;
                if (error !== "" && error !== undefined) {
                    this.$Message.error(error);
                }
                let related = q.related;
                let JWTKey = q.JWTKey;
                if (related && related === "1") {
                    if (JWTKey !== "" && JWTKey !== undefined) {
                        getJWT({ JWTKey: JWTKey }).then(res => {
                            if (res.success) {
                                this.socialLogining = true;
                                this.setStore("accessToken", res.result);
                                // 获取用户信息
                                userInfo().then(res => {
                                    if (res.success === true) {
                                        // 避免超过大小限制
                                        delete res.data.permissions;
                                        let roles = [];
                                        res.result.roles.forEach(e => {
                                            roles.push(e.name);
                                        });
                                        this.setStore("roles", roles);
                                        // 保存7天
                                        Cookies.set("userInfo", JSON.stringify(res.result), {
                                            expires: 7
                                        });
                                        this.setStore("userInfo", res.result);
                                        this.$store.commit("setAvatarPath", res.result.avatar);
                                        // 加载菜单
                                        util.initRouter(this);
                                        this.$router.push({
                                            name: "home_index"
                                        });
                                    } else {
                                        this.socialLogining = false;
                                        this.$Message.error("使用第三方账号登录失败");
                                    }
                                });
                            } else {
                                this.socialLogining = false;
                                this.$Message.error("使用第三方账号登录失败");
                            }
                        });
                    }
                } else {
                    this.socialLogining = false;
                }
            },
            showAccount() {
                this.$Notice.info({
                    title: "体验账号密码",
                    desc:
                        "账号：admin 密码：123456",
                    duration: 10
                });
            },
            showMessage() {
                this.$Notice.success({
                    title: "已升级至iView3.0",
                    desc: "完善多项功能，包括部门管理、定时任务、前端模版等 修复已知BUG",
                    duration: 5
                });
            }
        },
        mounted() {
           // this.showAccount();
            this.handleLoginConfig();
            this.relatedLogin();
        }
    };
</script>

<style lang="less">
  @import "login.less";
</style>
